package com.netease.financial.ui.activity;

import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.netease.financial.NfsApplication;
import com.netease.financial.R;
import com.netease.financial.base.customerservice.CustomerServiceHelper;
import com.netease.financial.base.customerservice.UnreadCountChangeListener;
import com.netease.financial.base.lockpattern.LockPatternHelper;
import com.netease.financial.base.push.PushHelper;
import com.netease.financial.base.suspendwindow.ChatBallUtil;
import com.netease.financial.common.util.NfsLog;
import com.netease.financial.internal.di.components.ApplicationComponent;
import com.netease.financial.internal.di.modules.ActivityModule;
import com.netease.financial.navigation.Navigator;

import butterknife.ButterKnife;
import cn.bingoogolapple.badgeview.BGABadgeImageView;

/**
 * Created by hzwuyufeng on 1/22/16.
 */
public class BaseAppCompatActivity extends AppCompatActivity {
    private static final String TAG = BaseActivity.class.getSimpleName();

    private TextView mLeftNavigationItem;
    private TextView mCloseNavigationItem;
    private TextView mTitleTextView;
    private BGABadgeImageView ivBadgeCustomerService;

    // Unread customer service message count change listener
    private UnreadCountChangeListener unreadCountChangeListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getApplicationComponent().inject(this);
        handleChatBall();
        handleLockPattern();
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        initSupportActionBar();
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        initSupportActionBar();
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        super.setContentView(view, params);
        initSupportActionBar();
    }

    @Override
    protected void onResume() {
        super.onResume();
        PushHelper.onResume(this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        PushHelper.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterCustomerService();
    }

    @Override
    public void setSupportActionBar(Toolbar toolbar) {
        super.setSupportActionBar(toolbar);
        initActionBar(toolbar);
    }

    private void registerCustomerService() {
        if (unreadCountChangeListener == null) {
            setCustomerServiceBadgeState(CustomerServiceHelper.getUnreadCount());
            // 监听云商服未读消息数量变更事件
            unreadCountChangeListener = new UnreadCountChangeListener() {
                @Override
                public void onUnreadCountChange(int i) {
                    setCustomerServiceBadgeState(i);
                }
            };
            CustomerServiceHelper.addUnreadCountChangeListener(unreadCountChangeListener, true);
        }
    }

    private void setCustomerServiceBadgeState(int count) {
        if (count > 0) {
            ivBadgeCustomerService.showCirclePointBadge();
        } else {
            ivBadgeCustomerService.hiddenBadge();
        }
    }

    private void unregisterCustomerService() {
        if (unreadCountChangeListener != null) {
            CustomerServiceHelper.addUnreadCountChangeListener(unreadCountChangeListener, false);
        }
    }

    private void initSupportActionBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        NfsLog.d(TAG, "toolbar" + toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
    }

    private void initActionBar(View customView) {
        mLeftNavigationItem = ButterKnife.findById(customView, R.id.tv_nav_back);
        if (mLeftNavigationItem != null) {
            Drawable drawable = getResources().getDrawable(R.drawable.abc_ic_menu_nav_back_dark);
            setNavBackDrawable(drawable);
        }

        mCloseNavigationItem = ButterKnife.findById(customView, R.id.tv_nav_close);

        mTitleTextView = ButterKnife.findById(customView, R.id.tv_title);
        if (mTitleTextView != null) {
            String label = getActivityLabel();
            if (!TextUtils.isEmpty(label)) {
                mTitleTextView.setText(label);
            }
        }

        ivBadgeCustomerService = ButterKnife.findById(customView, R.id.btn_right);
        if (ivBadgeCustomerService != null) {
            registerCustomerService();
            ivBadgeCustomerService.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getNavigator().navigateToChatScreen(BaseAppCompatActivity.this);
                }
            });
        }

        initTextColor();
    }

    private void setNavBackDrawable(Drawable drawable) {
        if (mLeftNavigationItem != null) {
            if (drawable != null) {
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            }
            mLeftNavigationItem.setCompoundDrawables(drawable, null, null, null);
        }
    }

    private String getActivityLabel() {
        String label = null;
        try {
            label = getResources().getString(getPackageManager().getActivityInfo(getComponentName(), 0).labelRes);
            NfsLog.d(TAG, "label 000 = " + label);

        } catch (PackageManager.NameNotFoundException | Resources.NotFoundException e) {
            e.printStackTrace();
        }

        NfsLog.d(TAG, "label 111 = " + label);
        return label;
    }

    @SuppressWarnings("ResourceType")
    private void initTextColor() {
        int[] attrs = new int[]{R.attr.leftActionBarItemDrawable, R.attr.leftActionBarItemTextColor, R.attr.middleActionBarItemTextColor};
        TypedArray typedArray = obtainStyledAttributes(attrs);
        Drawable drawable = typedArray.getDrawable(0);
        if (drawable != null && mLeftNavigationItem != null) {
            setNavBackDrawable(drawable);
        }
        ColorStateList leftTextColorStateList = typedArray.getColorStateList(1);
        NfsLog.d(TAG, "leftTextColorStateList:" + leftTextColorStateList);
        NfsLog.d(TAG, "typedArray.length:" + typedArray.length());

        if (leftTextColorStateList != null && mLeftNavigationItem != null) {
            mLeftNavigationItem.setTextColor(leftTextColorStateList);
        }
        ColorStateList middleTextColorStateList = typedArray.getColorStateList(2);
        NfsLog.d(TAG, "middleTextColorStateList:" + middleTextColorStateList);

        if (middleTextColorStateList != null && mTitleTextView != null) {
            mTitleTextView.setTextColor(middleTextColorStateList);
        }
        typedArray.recycle();
    }

    protected TextView getLeftNavigationItem() {
        return mLeftNavigationItem;
    }

    protected void enableLeftNavigationItem(boolean enable) {
        if (mLeftNavigationItem == null) {
            return;
        }
        if (enable) {
            mLeftNavigationItem.setVisibility(View.VISIBLE);
            mLeftNavigationItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        } else {
            mLeftNavigationItem.setVisibility(View.INVISIBLE);
        }
    }

    protected TextView getCloseNavigationItem() { return mCloseNavigationItem; }

    protected BGABadgeImageView getRightNavigationItem() {
        return ivBadgeCustomerService;
    }

    protected TextView getTitleItem() {
        return mTitleTextView;
    }

    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        if (mTitleTextView != null) {
            mTitleTextView.setText(title);
        }
    }

    @Override
    public void setTitle(int titleId) {
        super.setTitle(titleId);
        if (mTitleTextView != null) {
            mTitleTextView.setText(titleId);
        }
    }

    private void handleChatBall() {
        if (shouldShowChatBall()) {
            ChatBallUtil.register(getClass().getName());
        }
    }

    private void handleLockPattern() {
        if (!shouldProtectedByLockPattern()) {
            LockPatternHelper.registerIntoWhiteList(getClass().getName());
        }
    }

    protected boolean shouldProtectedByLockPattern() {
        return true;
    }

    protected Navigator getNavigator() {
        return NfsApplication.getApplication().getNavigator();
    }

    //If there is no need to show chat ball in the subclass, please override this function.
    protected boolean shouldShowChatBall() {
        return true;
    }

    /**
     * Get the Main Application component for dependency injection.
     *
     * @return {@link ApplicationComponent}
     */
    protected ApplicationComponent getApplicationComponent() {
        return ((NfsApplication) getApplication()).getApplicationComponent();
    }

    /**
     * Get an Activity module for dependency injection.
     *
     * @return {@link ActivityModule}
     */
    protected ActivityModule getActivityModule() {
        return new ActivityModule(this);
    }
}
